<template>
  <div class="view-container">
    <div class="filter-container">
      <el-form
        :inline="true"
        :model="filterData"
        label-position="right"
        size="small"
        class="filter-form-inline"
        label-width="90px"
      >
        <el-row
          :gutter="24"
          style="margin-left: 0px; margin-right: 0px"
        >
          <el-col
            :span="5"
            style="padding-left: 0px"
          >
            <el-form-item
              label="产品状态"
              style="width: 100%"
            >
              <el-select
                v-model="filterData.productStatus"
                clearable
                style="width: 100%"
                placeholder="产品状态"
                @change="listSearch"
              >
                <el-option
                  label="全部"
                  value=""
                />
                <el-option
                  v-for="(item) in productStatusOption.filter(p => p.value === '2'||p.value === '-4')"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              label="产品线"
              style="width: 100%"
            >
              <el-select
                v-model="filterData.productLine"
                style="width: 100%"
                placeholder="产品线"
                @change="listSearch"
              >
                <el-option
                  label="全部"
                  :value="0"
                />
                <el-option
                  v-for="(itm) in productLineOptions"
                  :key="itm.id"
                  :label="itm.productLineName"
                  :value="itm.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              label="创建时间"
              style="width: 100%"
            >
              <date-range-picker
                v-model:date="filterData.date"
                style="width: 100%"
                type="daterange"
                clearable
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handlDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              label="关键字搜索"
              style="width: 100%"
            >
              <el-input
                v-model="filterData.keyWord"
                clearable
                placeholder="输入产品名称、通用名、别名、批准文号、产品编号"
              >
                <template #suffix>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="输入产品名称、通用名、别名、批准文号、产品编号关键字搜索"
                    placement="top"
                  >
                    <i class="iconfont icon-wenhao" />
                  </el-tooltip>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item style="width: 100%">
              <el-button
                class="border-btn"
                @click="reset"
              >重置</el-button>
              <el-button
                type="primary"
                class="main-btn"
                @click="listSearch"
              >搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div
      class="main-content"
      style="padding-top: 0px;"
    >
      <div class="list-container">
        <table-view
          header-cell-class-name="table-header"
          :data="listData.list"
          border
          :cell-style="cellStyle"
          @row-click="rowClick"
        >
          <el-table-column
            prop="productNumber"
            label="产品编号"
            fixed="left"
            :min-width="140"
            header-align="center"
            align="center"
          />
          <el-table-column
            :min-width="120"
            show-overflow-tooltip
            prop="productName"
            label="商品名"
            fixed="left"
            header-align="center"
          />
          <el-table-column
            prop="productPopularName"
            label="通用名"
            :min-width="120"
            show-overflow-tooltip
            fixed="left"
            header-align="center"
          />
          <el-table-column
            :min-width="100"
            show-overflow-tooltip
            prop="packSpecs"
            label="包装规格"
            header-align="center"
          />
          <el-table-column
            :min-width="140"
            show-overflow-tooltip
            prop="producer"
            label="生产厂家"
            header-align="center"
          />
          <el-table-column
            prop="sellUnit"
            label="计价单位"
            :width="90"
            show-overflow-tooltip
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <span> {{ getLabel('sell_unit', scope.row.sellUnit) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :width="110"
            prop="marketPrice"
            label="市场价（元）"
            header-align="center"
            align="center"
          />
          <el-table-column
            :width="110"
            prop="medicalInsurancePrice"
            label="医保价（元）"
            header-align="center"
            align="center"
          />
          <el-table-column
            prop="productLine"
            label="所属产品线"
            :min-width="100"
            show-overflow-tooltip
            header-align="center"
          >
            <template #default="scope">
              <span> {{ scope.row.productLineDetail?.productLineName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="productAttribute"
            label="产品属性"
            :min-width="100"
            show-overflow-tooltip
            header-align="center"
          >
            <template #default="scope">
              <span> {{ getLabel('product_attribute', scope.row.productAttribute) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="creatorName"
            label="创建人"
            :min-width="140"
            header-align="center"
            align="center"
            sortable
          />
          <el-table-column
            prop="createdAt"
            label="创建时间"
            :width="140"
            header-align="center"
            align="center"
            sortable
          >
            <template #default="scope">
              <span> {{ dateFormat('yyyy-mm-dd HH:MM', scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="productStatus"
            label="状态"
            :min-width="120"
            header-align="center"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <product-status
                style="line-height:20px;"
                :datas="scope.row"
              />
            </template>
          </el-table-column>
          <!--
            <el-table-column
            label="操作"
            fixed="right"
            header-align="center"
            :min-width="180"
          >
            <template #default="scope">
              <template v-if="scope.row.productStatus!=='-4'&&scope.row.flowStatus!=='DOING'">
                <el-button
                  v-auth="{v: ['crm:product:edit'], bool: scope.row.productStatus==='-1'||scope.row.productStatus==='-2'}"
                  type="text"
                  @click="editProduct(scope.row)"
                >编辑</el-button>
                <el-button
                  v-auth="{v: ['crm:product:change'], bool: scope.row.productStatus==='2'}"
                  type="text"
                  @click="changeProduct(scope.row)"
                >变更</el-button>
                <el-button
                  v-auth="{v: ['crm:product:soldOut'], bool: scope.row.productStatus==='2'}"
                  type="text"
                  class="danger"
                  @click="soldOutProduct(scope.row)"
                >下架</el-button>
                <el-button
                  v-auth="{v: ['crm:product:delete'], bool: scope.row.productStatus==='-1'||scope.row.productStatus==='-2'}"
                  type="text"
                  class="danger"
                  @click="deleteProduct(scope.row)"
                >删除</el-button>
              </template>

            </template>
          </el-table-column>
          -->
        </table-view>
        <Pagination
          v-model:page="filterData.page"
          v-model:limit="filterData.pageSize"
          style="display: flex; justify-content: flex-end"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 创建编辑弹框 -->
    <createOrEdit
      ref="createChangeDialog"
      @success="createEditSuccess"
    />
    <!-- 下架弹框 -->
    <soldOutProductDialog
      ref="soldOutDialog"
      @soldOutSuccess="soldOutSuccess"
    />
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRouter } from 'vue-router'
import { crmStore } from '@CRM/store'

export default defineComponent({
  name: 'BusinessList',
  components: {
    createOrEdit: defineAsyncComponent(() =>
      import('../modules/createOrEdit.vue')
    ),
    soldOutProductDialog: defineAsyncComponent(() =>
      import('../modules/soldOutProductDialog.vue')
    ),
    productStatus: defineAsyncComponent(() =>
      import('../modules/productStatus.vue')
    ),
  },
  setup(props, context) {
    const api = inject('api')
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const createChangeDialog = ref(null)
    const soldOutDialog = ref(null)

    var reactiveData = reactive({
      productLineOptions: [],
      filterData: {
        date: [],
        productStatus: '',
        productLine: 0,
        keyWord: '',
        startTime: null,
        endTime: null,
        from: '2', // 和产品共用
        page: 1,
        pageSize: 20,
      },
      productStatusOption:
        crmStore.getters['dictionary/getDictionary']['product_status'] || [],
    })
    var listData = reactive({
      list: [],
    })
    var total = ref(0)
    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event)
      if (column.label === '操作') return
      router.push({
        name: 'marketDetail',
        query: {
          productId: row.id,
          productAttribute: row.productAttribute,
        },
      })
    }
    // 时间范围变化
    const handlDateChange = (val) => {
      console.log(val)
      if (val && val.length) {
        reactiveData.filterData.startTime = val[0]
        reactiveData.filterData.endTime = val[1]
      } else {
        reactiveData.filterData.startTime = null
        reactiveData.filterData.endTime = null
      }
      getList()
    }
    // 产品线
    const getProductLine = () => {
      api.system.PRODUCTLINE_LIST().then((res) => {
        if (res.code === 0) {
          reactiveData.productLineOptions = res.data.list
        }
      })
    }
    const reset = () => {
      reactiveData.filterData = {
        date: [],
        productStatus: '',
        productLine: 0,
        keyWord: '',
        startTime: null,
        endTime: null,
        from: '2',
        page: 1,
        pageSize: 20,
      }
      getList()
    }
    const listSearch = () => {
      reactiveData.filterData.page = 1
      getList()
    }
    const createEditSuccess = () => {
      getList()
    }
    const getList = () => {
      console.log(api)
      api.product.PRODUCT_LIST(reactiveData.filterData).then((res) => {
        console.log(res)
        if (res.code === 0) {
          listData.list = res.data.list || []
          total.value = res.data.total || 0
        }
      })
    }
    // 删除产品
    const deleteProduct = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '数据删除后不可恢复，确定删除？',
          title: '产品删除',
        })
        .then(() => {
          api.product
            .PRODUCT_DELETE({
              id: row.id,
            })
            .then((res) => {
              if (res.code) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              } else {
                getList()
              }
            })
        })
        .catch((err) => {
          console.log(err)
        })
    }
    // 创建产品
    const createProduct = () => {
      console.log(createChangeDialog)
      createChangeDialog.value.open('create')
    }
    // 变更产品
    const changeProduct = (row) => {
      createChangeDialog.value.open('change', row.id)
    }
    // 编辑产品
    const editProduct = (row) => {
      createChangeDialog.value.open('edit', row.id)
    }
    // 下架产品
    const soldOutProduct = (row) => {
      console.log('下架产品')
      soldOutDialog.value.open(row.id)
    }
    // 下架成功
    const soldOutSuccess = () => {
      console.log('下架成功')
      getList()
    }

    onMounted(() => {
      getProductLine()
      getList()
    })

    return {
      ...toRefs(reactiveData),
      listData,
      total,
      createChangeDialog,
      soldOutDialog,
      cellStyle,
      rowClick,
      getList,
      listSearch,
      createEditSuccess,
      createProduct,
      deleteProduct,
      soldOutProduct,
      changeProduct,
      editProduct,
      soldOutSuccess,
      handlDateChange,
      reset,
    }
  },
})
</script>
